const mongoose = require('mongoose');
var Order = require('../models/order.model');

exports.create = function(req, res, next) {
    const order = new Order(req.body);
    order.save().then((data) => res.json(data));
}

exports.update = function(req, res, next) {
    const id = req.params.id;

    Order.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => {
        res.json(data);
    })
}

exports.remove = function(req, res, next) {
    const id = req.params.id;
    Order.findByIdAndDelete(id, (err, data) => {
        res.json(data);
    })
}

exports.removes = function(req, res, next) {
    const ids = req.body.ids.split(',');
    // console.log(ids);
    if (ids.length > 0) {
        Order.remove({ _id: { $in: ids } }).then(data => {
            res.json({ "message": "数据已删除!" })
        })
    }
}


exports.list = function(req, res, next) {
    var page = req.body.page ? req.body.page : 1;
    var rows = req.body.rows ? req.body.rows : 10;

    // var queryCondition = {};
    // if(req.body.name){
    //   queryCondition = {
    //     "name": new RegExp(name,'i')
    //   }
    // }
    var queryCondition = {};
    // console.log(req.body)
    if (req.body.productname && req.body.productname.trim().length > 0) {
        queryCondition = {
            "productname": new RegExp(req.body.productname, 'i')
        }
    }

    if (req.body.productId && req.body.productId.trim().length > 0) {
        queryCondition = Object.assign(queryCondition,{
            "productId": req.body.productId
        })
    }

    Order.paginate(queryCondition, { page: +page, limit: +rows }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    });
}

exports.get = function(req, res, next) {
    const id = req.params.id;
    Order.findById(id).then(data => {
        res.json(data);
    })
}